package com.hzgj.bcl.soa.controller;

import com.google.common.collect.Maps;
import com.hzgj.bcl.soa.CliLoader;
import com.hzgj.bcl.soa.command.CommandInvoker;
import com.hzgj.bcl.soa.controller.logic.PageLogic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * Created by Administrator on 2016/9/5.
 */
@Controller
public class CliController {

    @Autowired
    CliLoader cliLoader;

    private static Logger logger = LoggerFactory.getLogger(CliController.class);

    @RequestMapping("/ajax/{page}")
    public String soaPage(@PathVariable String page, Model model, HttpServletRequest request) {
        PageLogic pageLogic = cliLoader.getPageLogic(page);
        if (pageLogic != null) {
            pageLogic.handle(request, model);
        } else {
            Enumeration<String> enumeration = request.getParameterNames();
            while (enumeration.hasMoreElements()) {
                String param = enumeration.nextElement();
                model.addAttribute(param, request.getParameter(param));
            }
        }
        return page;
    }

    @RequestMapping("/service-relation")
    public String service_relation() {
        return "ajax/plugins";
    }

    @RequestMapping("/soa/{command}")
    public void command(HttpServletRequest request, HttpServletResponse response, @PathVariable String command) {
        command(request, response, command, null);
    }

    @RequestMapping("/soa/{command}/{scmd}")
    public void command(HttpServletRequest request, HttpServletResponse response, @PathVariable String command, @PathVariable String scmd) {
        writeJson(CommandInvoker.execute(command, scmd, Maps.newHashMap(request.getParameterMap())), response);
    }

    public static void writeJson(String o, HttpServletResponse response) {
        try {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(o);
            response.getWriter().flush();

        } catch (IOException e) {
            logger.error("{}", e);
        }
    }
}
